﻿/* Example of using ANTLR to build DLR expression trees to execute math expressions.
 * Variables are supported.
 * Every line must end with a semi-colon.
 */

using System;
using Antlr.Runtime;
using Antlr.Runtime.Tree;
using System.IO;
using System.Text;

namespace ANTLR01
{
    public class GlobalScope : SimpleObject
    {
        static GlobalScope()
        {
            Instance = new GlobalScope();
        }

        private GlobalScope()
        {
        }

        public static dynamic Instance { get; private set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            dynamic scope = new SimpleObject();

            while (true)
            {
                Console.Write("> ");
                var text = Console.ReadLine();
                if (text == null)
                {
                    break; // Ctrl+Z to exit
                }
                if (text == string.Empty)
                {
                    continue;
                }
                
                try
                {
                    var input = new ANTLRStringStream(text + '\n');
                    var lexer = new ExprLexer(input);
                    var tokens = new CommonTokenStream(lexer);
                    var parser = new ExprParser(tokens);
                    var r = parser.prog();

                    // Walk the resulting tree:
                    var tree = (CommonTree)r.Tree;
                    var nodes = new CommonTreeNodeStream(tree);
                    var walker = new Eval(nodes);
                    var func = walker.prog();

                    scope.Expression = func;

                    Console.WriteLine(scope());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}